#include "WijiDOM.h"
#include <QFile>
#include <QDomDocument>
#include <QDomElement>
#include "WijiSettings.h"
#include "WijiUi.h"
#include <QScriptValue>
#include <QMessageBox>
#include <QRegExp>
WijiDOM::WijiDOM(QObject *parent) :
    QObject(parent)
{
}
QString WijiDOM::parseFile(QString filename) {
    QFile file(filename);
    if (!doc.setContent(&file,true,&errorStr, &errorLine, &errorColumn)) {
        //qDebug() << "An Error Occured while parsing: " << filename;
        //qDebug() << QObject::tr("Parse Error at: Line(%1) Col(%2)").arg(errorLine).arg(errorColumn);
        //qDebug() << "QDom Says:" << errorStr;
        return QString("Loading of file "+filename+" failed");
    }
    QDomElement root = doc.documentElement();
    parseElement(root);
    //qDebug() << "Parsing Complete";
    QString result = WijiSettings::getSelf()->parseResult(doc.toString());
    //qDebug() << result;
    return result;
}
QString WijiDOM::parseHtml(QString html) {
	if(!doc.setContent(html))
	{
		return QString("Loading of HTML failed");
	}
	QDomElement root = doc.documentElement();
	parseElement(root);
        QString result = WijiSettings::getSelf()->parseResult(doc.toString());
	return result;
}


QDomElement WijiDOM::parseElement(QDomElement e) {
    QDomNode node = e.firstChild();
    QScriptValue result;
    while (!node.isNull()) {
        //qDebug() << "Still in loop";
        if (!node.isElement()) {

            //continue; //i.e. we are only interested in elements right now.
        }
        QString fileName;
        fileName = WijiSettings::getSelf()->getValue("system_scripts").toString() +
                   "/" +
                   WijiSettings::getSelf()->getValue("custom_tags").toString() +
                   "/" +
                   node.toElement().tagName().toLower() +
                   "." +
                   WijiSettings::getSelf()->getValue("qt_script_extension").toString();
                    // which should produce something like system/scripts/custom_tags/include.qs
        if (QFile::exists(fileName)) {
            //qDebug() << "File exists.";
                QDomNamedNodeMap attributes = node.attributes();
                QDomNode tmpnode;
                QDomAttr tmpattr;
                QStringList attrobj;
                for (int i = 0; i < attributes.length();i++) {
                    //qDebug() << "Looping Attrs";
                    tmpnode = attributes.item(i);
                    if (!tmpnode.isAttr())
                        continue;
                    tmpattr = tmpnode.toAttr();
                    attrobj << tmpattr.name() + ": '" + tmpattr.value() + "'";
                }
                QString innards = node.toText().data();

                QRegExp rx("\"");
                QRegExp rx2("\n");
                int pos = 0;
                while ((pos = rx.indexIn(innards, pos)) != -1) {
                    innards.replace(rx,"\\\"");
                }
                pos = 0;
                while ((pos = rx2.indexIn(innards, pos)) != -1) {
                    innards.replace(rx2,"\\n");
                }
                attrobj << "content:\"" + innards + "\"" ;
                QString code = "var attributes = {" + attrobj.join(",") +"};";
                //qDebug() << "Code:" << code;
                WijiUi::getSelf()->scripter.engine.evaluate(code);
                if (WijiUi::getSelf()->scripter.engine.hasUncaughtException()) {
                    QScriptValue exception = WijiUi::getSelf()->scripter.engine.uncaughtException();
                    QMessageBox::critical(0,QObject::tr("Script Error"),QString(QObject::tr("Engine threw an uncaught exception. ")) + exception.toString());
                }
                result = WijiUi::getSelf()->scripter.runQtScript(fileName);

                QDomDocument td;
                td.setContent(result.toString());
                QDomNode pnode = node.parentNode();
                if (pnode.isNull()) {
                    qDebug() << "pnode is null..";
                }
                QDomNode fchild = td.firstChild();
                pnode.replaceChild(fchild,node);
                QDomNode c = fchild.nextSibling();
                while (!c.isNull()) {
                    qDebug() << c.toElement().tagName();
                    pnode.appendChild(c);
                    c = c.nextSibling();
                }
        }
        if (node.hasChildNodes()) {
            parseElement(node.toElement());
        }
        node = node.nextSibling();
    }
    return e;
}

